package org.moon.framework.autoconfigure.oss.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.ftp.Ftp;
import cn.hutool.extra.ftp.FtpException;
import cn.hutool.extra.ftp.FtpMode;
import org.moon.framework.autoconfigure.oss.OssService;
import org.moon.framework.autoconfigure.oss.OssTemplate;
import org.moon.framework.autoconfigure.oss.props.OssProperties;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.List;

/**
 * Ftp 文件客户端
 *
 * @author 芋道源码
 */
public class FtpOssService implements OssService {

    private Ftp ftp;
    private OssProperties ossProperties;

    public FtpOssService(OssProperties ossProperties) {
        this.ossProperties = ossProperties;
        // 初始化 Ftp 对象
        this.ftp = new Ftp(ossProperties.getHost(), ossProperties.getPort(), ossProperties.getUserName(), ossProperties.getPassword(),
                CharsetUtil.CHARSET_UTF_8, null, null, FtpMode.valueOf(ossProperties.getMode()));
    }

    @Override
    public String upload(byte[] content,String originalName) {
        // 执行写入
        String filePath = getFilePath(ossProperties.getBasePath(),originalName);
        String fileName = FileUtil.getName(filePath);
        String dir = StrUtil.removeSuffix(filePath, fileName);
        ftp.reconnectIfTimeout();
        boolean success = ftp.upload(dir, originalName, new ByteArrayInputStream(content));
        if (!success) {
            throw new FtpException(StrUtil.format("上传文件到目标目录 ({}) 失败", filePath));
        }
        String link = formatFileUrl(ossProperties.getDomain(),ossProperties.getId(), filePath);
        insert(ossProperties.getId(),originalName,link, OssTemplate.FileStorageEnum.FTP);
        return link;
    }

    @Override
    public void delete(String link) {
        String filePath = getFilePath(link,ossProperties.getDomain(),ossProperties.getId());
        ftp.reconnectIfTimeout();
        ftp.delFile(filePath);
        delete(ossProperties.getId(),link);
    }

    @Override
    public void batchDelete(List<String> links) {
        for(String link:links){
            delete(link);
        }
    }

    @Override
    public byte[] getContent(String link) {
        String filePath = getFilePath(link,ossProperties.getDomain(),ossProperties.getId());
        String fileName = FileUtil.getName(filePath);
        String dir = StrUtil.removeSuffix(filePath, fileName);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ftp.reconnectIfTimeout();
        ftp.download(dir, fileName, out);
        return out.toByteArray();
    }
}